from core.ws_response import Text, Stop, WsObject, Custom
from ssh import remoteSSHClient

SHELL_MAPPING={""}
def connect(req):

    print "this is connect func"
    name = req.param("name")
    password = req.param("password")
    ip = req.param("ip")
    try:
        client = remoteSSHClient(ip, name, password)
        req.app("ssh", client)
        return [Text(data={"status": "SUCCESS", "func": "showtty"}), 
                        Custom(recv_result, show_func="showResult", exe_func="exeResult", client = client)]
    except :
        import sys
        print sys.exc_info()
        msg = "can not connect server %s for user = %s "% (ip, name)
        return Text(data={"message": msg , "status": "FAIL", "func": "showtty"})
        

def sendKeycode(req):
    print "this is send key code"
    keycode = req.get_data("keycode")
    ssh_client = req.app("ssh")
    return Custom(send_exec, client = ssh_client, keycode = keycode)

"""
def sendCmd(req):
    print "this is sendCmd"
    command = req.get_data("command")
    
    if not command:
        command = ""
    ssh_client = req.app("ssh")
    print repr(command)
    if ssh_client:
        return Custom(send_exec, client = ssh_client, command = command)
    else:
        raise RuntimeError("not found ssh_client")
"""


def send_exec(current, to_sessions, data, **kargs):
    print "this is send_exec"
    client = kargs["client"]
    key = kargs.get("keycode", "")
    if key:
        cmd = client.convert(key)
        client.channel.send(cmd)
    print "after send"

def recv_result(current, to_sessions, data, **kargs):
    print "this is recv_result"
    showfunc = kargs["show_func"]
    exefunc = kargs["exe_func"]
    client = kargs["client"]

    i = 0
    while True:
        result_buffer = client.channel.recv(1024)
        if client.channel.exit_status_ready():
            break
        print i
        result = client.parser(result_buffer, showfunc, exefunc)
        current.send_data(result)
        i += 1

def close(req):
    print "this is close in sshServer.py"
    ssh_client = req.app("ssh")
    ssh_client.close()
    return Stop()

